import { UserLayout, BasicLayout, RouteView, BlankLayout, PageView } from '@/layouts'
export function actionToObject(json) {
  try {
    return JSON.parse(json)
  } catch (e) {
    console.log('err', e.message)
  }
  return []
}
const constantRouterComponents = {
  // 基础页面 layout 必须引入
  BasicLayout: BasicLayout,
  BlankLayout: BlankLayout,
  RouteView: RouteView,
  PageView: PageView,
  UserLayout: UserLayout,
  UserRoleList: () => import('@/views/user/role/List'),
  UserRoleDetail: () => import('@/views/user/role/Detail'),
  UserList: () => import('@/views/user/user/List'),
  UserDetail: () => import('@/views/user/user/List'),
  UserOperate: () => import('@/views/user/Operate'),
}

export const notFoundRouter = {
  path: '*',
  redirect: '/404',
  hidden: true,
}

// 将后台传来的路由数据转换成规格的路由格式
export const generator = (routerMap, parent) => {
  return routerMap.map((item) => {
    const currentRouter = {
      // 路由地址 动态拼接生成如 /dashboard/workplace
      path: `${(parent && parent.path) || ''}/${item.key}`,
      // 路由名称，建议唯一
      name: item.name || item.key || '',
      // 该路由对应页面的 组件

      component: constantRouterComponents[item.component || item.key],
      // meta: 页面标题, 菜单图标, 页面权限(供指令权限用，可去掉)
      meta: {
        title: item.title,
        icon: item.icon || undefined,
        keepAlive: item.keepAlive === 1,
        permission: (item.name && [item.name]) || null,
      },
      hidden: item.hidden === 1,
      hideChildrenInMenu: item.hideChildrenInMenu === 1,
    }
    // 为了防止出现后端返回结果不规范，处理有可能出现拼接出两个 反斜杠
    currentRouter.path = currentRouter.path.replace('//', '/')
    // 重定向
    item.redirect && (currentRouter.redirect = item.redirect)
    // 是否有子菜单，并递归处理
    if (item.nav && item.nav.length > 0) {
      // Recursion
      currentRouter.children = generator(item.nav, currentRouter)
    }
    return currentRouter
  })
}
